

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


//从URL下载图片并保存到指定路径。
public class FileUtils {
    public static void saveImage(String url, String savePath) throws IOException {
        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    //检查目录是否存在，不存在则创建。
    public static void ensureDirectoryExists(String dirPath){
        File dir =new File(dirPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
    }


    //将下载记录追加到download_log.txt（格式：时间 + 图片URL + 保存路径）。
    public static void appendLog(String log){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String logEntry = time + " " + log+"\n" ;

        try(FileWriter fw =new FileWriter("download_log.txt",true);
            BufferedWriter bw =new BufferedWriter(fw)){
            bw.write(logEntry);
        } catch (IOException e){
            System.out.println("记录日志时发生错误："+e.getMessage());
        }


    }
}